package com.bree.erp.service.stateless;

import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Group;
import com.bree.erp.entity.GroupType;
import com.bree.erp.entity.User;
import com.bree.erp.service.GroupService;

@Stateless
public class GroupServiceBean implements GroupService {
	
	@PersistenceContext()
	private EntityManager em;
	
	public GroupServiceBean() {
		
	}
	
	public GroupServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public Group create(User user, GroupType groupid) {
		Group group = new Group();
		
		group.setGroupId(groupid);
		group.setUser(user);
		
		em.persist(group);
		return group;
	}

	@Override
	public void delete(Group group) {
		
		Group rem = em.find(Group.class, group.getId());
		
		rem.setUser(null);
		em.remove(rem);
		
	}
	
	@Override
	public List<Group> list() {
		TypedQuery<Group> query = em.createQuery("SELECT g FROM Group g", Group.class);
		return query.getResultList();
	}

	@Override
	public Collection<Group> findByGroupType(GroupType type) {
		TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_GROUPS_BY_TYPE, Group.class)
				.setParameter("groupId", type);
		
		return query.getResultList();
	}

	@Override
	public Group read(Long id) {
		
		return em.find(Group.class, id);
	}

	@Override
	public Group update(Long id, User user, GroupType groupid) {
		Group group = read(id);
		
		group.setGroupId(groupid);
		group.setUser(user);
		
		return group;
	}

	@Override
	public Group read(String userid, GroupType groupid) {
		
		User user = em.find(User.class, userid);

		TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_GROUP_BY_USERTYPE, Group.class)
				.setParameter("user", user)
				.setParameter("groupId", groupid);
		
		try {
			return query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

}
